package com.zheng.blogsystem.pointtestclient.okhttp;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.zheng.blogsystem.pointtestclient.base.Constants;
import okhttp3.Call;
import okhttp3.Cookie;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtil {

    public final static int READ_TIMEOUT = 30;
    public final static int CONNECT_TIMEOUT = 30;
    public final static int WRITE_TIMEOUT = 30;
    private final static String Accept_Json = "application/json; charset=utf-8";
    private final static String Accept_param = "application/x-www-form-urlencoded; charset=utf-8";

        public static final MediaType JSON_Param = MediaType.parse(Accept_param);
    public static final MediaType JSON_Json = MediaType.parse(Accept_Json);
    private static final byte[] LOCKER = new byte[0];
    public static OkHttpUtil mInstance;
    private OkHttpClient mOkHttpClient;
    private String cookie;

    private static final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

    /**
     * 自定义网络回调接口
     */
    public interface NetCall {
        void success(Call call, Response response) throws IOException;

        void failed(Call call, IOException e);
    }

    public OkHttpUtil() {
        OkHttpClient.Builder ClientBuilder = new OkHttpClient.Builder();
        ClientBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);//读取超时 单位s
        ClientBuilder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);//连接超时 单位s
        ClientBuilder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);//写入超时  单位 s
        mOkHttpClient = ClientBuilder.build();
    }

    /**
     * 单例模式获取OkHttpUtil
     *
     * @return
     */
    public static OkHttpUtil getInstance() {
        synchronized (LOCKER) {
            if (mInstance == null) {
                mInstance = new OkHttpUtil();
            }
            return mInstance;
        }
    }


    /**
     * @param Url_point URL地址
     * @param json      请求参数
     * @return response 返回请求结果
     */

    public Response postRequest(String Url_point, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON_Json, json);
        Request request = new Request.Builder()
                .addHeader("Accept", Accept_Json)
                .url(Constants.BASE_UIL+Url_point)
                .post(body)
                .build();
        System.out.println("请求地址:" + request);
        return  mOkHttpClient.newCall(request).execute();


    }

    /**
     * @param Url_point URL地址
     * @param json      请求参数
     * @return response 返回请求结果
     */

    public Response getRequestLogin(String Url_point, String json) throws IOException {

        Request request = new Request.Builder()
                .addHeader("Accept", Accept_param)
                .url(Constants.BASE_UIL+Url_point+json)
                .build();
        System.out.println("请求地址:" + request);
        return mOkHttpClient.newCall(request).execute();

    }

    /**
     * @param Url_point URL地址
     * @return response 返回请求结果
     */

    public Response getRequest(String Url_point) throws IOException {

        Request request = new Request.Builder()
                .addHeader("Accept", "application/json;charset=utf-8")
                .url(Constants.BASE_UIL+Url_point)
                .build();
        System.out.println("请求地址:" + request);
        Response response = mOkHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response;
        } else {
            throw new IOException("Unexpected code " + response);
        }

    }

    /**
     * 提交文件
     *
     * @param url
     * @param file
     * @return
     * @throws IOException
     */
    public Response postFile(String url, File file) throws IOException {
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .build();
        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + UUID.randomUUID())
                .addHeader("filepath", file.getPath())
                .url(url)
                .post(requestBody)
                .build();
        Response response = mOkHttpClient.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        return response;
    }
}